import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ZhongJinTao
 * Date: 2024-03-13
 * Time: 19:17
 */
public class TcpEchoClient {
    private Socket socket = null;

    public TcpEchoClient(String serverIp, int serverPort) throws IOException {
        socket = new Socket(serverIp, serverPort);
    }

    public void start() throws IOException {
        System.out.println("客户端启动");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            Scanner scannerConsole = new Scanner((System.in));
            Scanner scannerNetwork = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream)) {
            while (true) {
                //这里的流程和UDP的客户端类似
                //1、从控制台读取输入的字符串
                System.out.println("->");
                if(!scannerConsole.hasNext()) {
                    break;
                }
                String request = scannerConsole.next();
                //2、把请求发给服务器，这里需要使用 println 来发送，为了让发送的请求末尾带有 \n
                //这里是和服务器的 scanner.next 呼应的。
                writer.println(request);
                //通过这个flush主动刷新缓冲器，确保数据真的发送出去了
                //3、从服务器读取响应，这里也是和服务器返回响应的逻辑对应
                String response = scannerNetwork.next();
                //4、把响应显示出来
                System.out.println(response);
            }
        }
    }

}
